<template>

  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="search">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table ref="tableData" :row-key="row => row.userId" highlight-current-row v-loading="loading" :data="tableData"
        @row-click="handleEdit" @selection-change="handleSelectionChange" @select="select" @select-all="selectAll"
        :select-on-indeterminate="king">
        <el-table-column type="selection" width="55" :reserve-selection="true"
          :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">{{ scoped.row.userId ? scoped.$index + 1 : '' }}</template>
        </el-table-column>
        <!-- <el-table-column prop="userId" label="用户ID" /> -->
        <el-table-column prop="realName" label="用户名" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="phone" label="手机号">
          <template v-if="scoped.row.userId" slot-scope="scoped">
            {{ scoped.row.phone ? scoped.row.phone : '--' }}
          </template>
        </el-table-column>
        <el-table-column width="450" label="操作">
          <template slot-scope="scoped">
            <span class="table-btns edit-btns successText" @click="edit(scoped.row)">修改</span>
            <span class="table-btns edit-btns successText" @click="resetPassword(scoped.row)">重置密码</span>
            <span class="table-btns del-btns errorText" @click="delOne(scoped.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :title="titleText + '用户信息'" :visible.sync="dialogFormVisible" :before-close="cancel" width="30%"
        :close-on-click-modal="false">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="realName">
            <el-input :disabled="formData.userId == 1" v-model="formData.realName" clearable placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input :disabled="formData.userId == 1" v-model="formData.account" clearable placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone" clearable placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item v-if="nowChanceStau !== 'edit'" label="密码" prop="password" >
            <el-input v-model="formData.password" clearable placeholder="请输入密码"/>
          </el-form-item>
          <el-form-item label="选择基地" prop="personNo">
            <el-select class="w100p" placeholder="请选择基地" filterable clearable :disabled="formData.userId == 1"
              v-model="formData.baseList" multiple>
              <el-option v-for="item in baseList" :key="item.value" :label="item.homeBaseName"
                :value="item.homeBaseId + ''">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';

import homeBaseApi from "@/api/basic-info-manage/homeBase";
import assignroleComponent from "../components/assign-rolle-component";
import DataAuthComponent from "../components/func-auth-user-component";
import DataAppAuthComponent from "../components/App-user-component";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import UserApi from "@/api/system-settings/user-manage";
import StaffApi from "@/api/basic-info-manage/staff";
export default {
  name: "UserManage",
  components: {
    MainSlot,
    BtnSlot,
    SearchForm,
    Pagination,
    DataAuthComponent,
    assignroleComponent,
    DataAppAuthComponent
  },
  mixins: [mymixin],
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.formData.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3-9][0-9]\d{8}$/;
        // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
        if (reg.test(value)) {
          callback();
        } else {
          // 具体错误信息没有提示
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    return {

      btnList: ['add', 'delete'],
      formItemList: [
        {
          label: '用户名称',
          type: 'input',
          param: 'realName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
      ],
      baseList: [],
      // 右侧权限展示1主界面,2功能权限,3数据权限,4分配角色
      nowpage: 1,
      // 操作按钮的逻辑及展示数据
      addActive: true,
      editActive: false,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      funcAuthActive: false,
      king: true,
      // 数据权限
      dataAuthActive: false,
      // 分配角色
      assignRoleActive: false,
      funcAppAuthActive: false,
      dialogDataAppAuthFormVisible: false,
      // table
      loading: true,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 员工姓名
      realName: "",
      // 是否能输入
      canInput: false,
      tableData: [],
      checkedIdList: [],
      selectedRoleId: '',
      formData: {
        baseList: []
      },
      rules: {
        phone: [{ required: true, min: 11, message: "手机号不足11位", trigger: "blur" },
        { validator: checkPhone, trigger: "blur" }],
        baseList: [{ required: true, message: "请选择基地", trigger: "blur" }],
        realName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur"
          }
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur"
          }
        ],
        newPasswords: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: validatePass2,
            trigger: "blur"
          }
        ]
      },
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedUserList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      dialogFormAssignVisible: false,
      dialogFormFuthDataVisible: false,
      staffData: [],
      userstu: ""
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau: {
      handler(flag) {
        if (flag == 'add') {
          this.$set(this.formData, 'staffId', '');
          this.$set(this.formData, 'realName', '');
          this.$set(this.formData, 'account', '');
          this.$set(this.formData, 'phone', '');
          this.$set(this.formData, 'personNo', '');
          this.$set(this.formData, 'password', '');
          this.$refs.formData && this.$refs.formData.resetFields()
        }
      }
    }
  },
  created() {
    // 获取表格数据
    this.queryPageList();
    this.selectData();
    this.queryHomeBase();
  },
  methods: {
    queryHomeBase() {
      homeBaseApi.queryByCondition({}).then(res => {
        console.log('---基地---', res);
        this.baseList = res.data
      })
    },
    userAdd() {
      this.userstu = "add";
    },
    users() {
      this.userstu = "";
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false;
    },
    // 获取下拉框数据
    selectData() {
      StaffApi.queryByCondition({ checkHomeBaseType: true }).then(res => {
        this.staffData = res.data;
      });
    },
    search(data) {
      this.realName = data.realName;
      this.queryPageList();
    },
    staffPerson(e) {
      if (!e) {
        this.$set(this.formData, "staffId", undefined);
      }
    },
    // 获取当前用户可查看基地列表
    getHomeBase() {
      // 获取顶级组织结构id
      homeBaseApi.queryByUserId().then(res => {
        if (res.length == 0 || res.data == []) {
          this.$message.warning("该账户下无基地权限，请联系管理员！")
          removeToken("token")
          this.$router.push({ path: "/login" })
        } else {
          //默认第一个基地
          // setToken("companyMark", res.data[0].code);
          // setToken("homeBaseId", res.data[0].homeBaseId);
          // setToken("homeBaseType", res.data[0].homeBaseType);
          // setToken("homeBaseName", res.data[0].homeBaseName);
          sessionStorage.setItem("homeBaseList", JSON.stringify(res.data));
        }
      })
    },
    queryPageList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          userType: '1' //运营
        }
      };
      if (this.realName) params.entity.realName = this.realName;
      UserApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.success === true) {
          let data = res.data || [];
          // 总条数
          this.totalSize = data.totalElements || 0;
          this.tableData = data.content || [];
          this.dialogFormVisible = false
        }
      });
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.queryPageList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    // 点击行触发
    handleEdit(row) {
      this.selectedRoleId = row.userId
      if (row.homeBaseIdListStr && row.homeBaseIdListStr.length > 0) {
        row['baseList'] = row.homeBaseIdListStr.split(',')
      } else {
        row['baseList'] = []
      }
      this.formData = JSON.parse(JSON.stringify(row));
    },
    faciStatus(e) {
      this.$confirm("是否禁用", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          let params = {
            idList: [e.userId]
          };
          UserApi.forbidden(params).then((res) => {
            if (res.success) {
              this.$message.success("修改成功！");
              this.closeDialog();
              this.resetActionBar();
              this.queryPageList();
            }
          });
          this.$nextTick(() => {
            setTimeout(() => {
              this.queryPageList();
            }, 300);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          this.queryPageList();
          this.resetActionBar();
        });
    },
    // 点击功能权限触发的方法
    funcAuthShow() {
      this.nowpage = 2;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      this.dialogFormFuthDataVisible = true;
      // this.saveActive = true;
    },
    // 点击数据权限触发的方法
    dataAuthShow() {
      this.nowpage = 3;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      this.saveActive = true;
    },
    // 点击了分配角色------------------------------有问题
    assignRoleShow(formData) {
      // this.nowpage = 4;
      this.dialogFormAssignVisible = true;
    },
    // king取消分配
    unallotment() {
      this.dialogFormAssignVisible = false
      this.assignRoleActive = false
      this.resetActionBar()
    },
    funcAppAuthShow() {
      this.dialogDataAppAuthFormVisible = true;
    },
    cancel() {
      this.closeDialog();
      this.formData = {};
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignUserActive = false;
      this.funcAuthActive = false;
      this.funcAppAuthActive = false;
      this.addActive = true;
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.resetActionBar()
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage();
      }
    },
    //单个删除用户
    delOne(row) {
      if (row.userId == '1') {
        this.$message('此账号不可以被删除!')
        return
      }
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          UserApi.delById({ id: row.userId }).then(res => {
            if (res.success === true) {
              this.resetActionBar()
              this.$message.success("删除成功！");
              this.assignRoleActive = false
              if ((this.totalSize - 1) % 10 == 0) {
                this.currentPage--
                this.queryPageList();
              } else {
                this.queryPageList();
              }
            }
          });
        })
        .catch(() => {
          // this.assignRoleActive = false
          this.resetActionBar()
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // king表格批量删除
    delmessage() {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          UserApi.delByListId({ idList: this.checkedIdList }).then(res => {
            if (res.success) {
              if ((this.totalSize - this.checkedIdList.length) % 10 == 0) {
                this.currentPage--
                this.queryPageList();
              } else {
                this.queryPageList()
              }
              this.$message.success("删除成功");
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          // this.assignRoleActive = false
          this.resetActionBar()
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });

    },
    select(list) {
      if (list.length == 1 && list[0].userId) {
        let id = list[0].userId
        this.selectedRoleId = id
        this.assignRoleActive = true;
        this.formData.userId = id
      } else {
        this.assignRoleActive = false
      }
      let notvalue = true
      list.forEach(item => {
        if (!item.userId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    selectAll(list) {
      this.assignRoleActive = false
      let emptyList = []
      let notvalue = true
      list.forEach(item => {
        if (item.userId) {
          return item.userId
        } else {
          emptyList.push(item)
          notvalue = false
          return
        }
      });
      if (notvalue === false) {
        this.king = true
      }
    },
    handleSelectionChange(list) {
      this.queryPageList()
      this.checkedIdList = [];
      let notvalue = true
      let emptyList = []
      this.checkedIdList = list.map(item => {
        if (item.userId) {
          return item.userId
        } else {
          notvalue = false
          emptyList.push(item)
          return ""
        }
      });
      if (notvalue === false) {
        return
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },

    cancelAssign() {
      this.closeDialog();
    },
    // 添加or修改
    save(formData) {
      if (this.formData.baseList && this.formData.baseList.length > 0) {
        this.formData['homeBaseIdListStr'] = this.formData.baseList.join(',')
      }
      if (this.formData.userId == '1') {
        this.$message('此账号不可以编辑!')
        return
      }
      if (!formData) return;
      this.$refs[formData].validate(async valid => {
        if (valid) {
          if (this.nowChanceStau === "edit" && this.nowpage === 1) {
            // this.formData.organizationNo = [sessionStorage.organizationNo];
            // this.formData.topOrganization = sessionStorage.topOrganization;
            if (this.formData.oldPassword !== undefined && this.formData.oldPassword !== "") {
              await this.editPass();
            }
            UserApi.edit(this.formData).then(res => {
              this.getHomeBase();
              if (res.success) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.resetActionBar();
                this.queryPageList();
              } else {
                this.$message.success(res.message);
                this.resetActionBar()
              }
            });
          } else if (this.nowChanceStau === "add" && this.nowpage === 1) {
            // 新增接口
            if (!this.formData.staffId) {
              let from = JSON.parse(JSON.stringify(this.formData));
              // this.$set(this.formData)
              this.formData = {
                ...from
              };
            }
            this.registerIofo(this.formData);
          }
        } else {
          // this.resetActionBar()
          return false;
        }
        // this.resetActionBar();
      });
    },
    // 修改密码
    editPass() {
      let zhurl =
        this.$baseurl.webServiceUrl + "v3/virtualSystem/v1/user/resetPassword";
      let data = `username=${this.formData.username}&oldPassword=${this.formData.oldPassword}&newPassword=${this.formData.newPassword}`;
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: getToken("databaseName"),
          accessToken: getToken("token"),
          organizationList: getToken("organizationList"),
          organizationNo: getToken("organizationNo"),
          virtualSystemNo: getToken("virtualSystemNo")
        },
        data: data
      }).then(res => {
        if (res.data.success) {
          this.queryPageList();
          this.$message.success("密码修改成功");
        } else {
          if (res.data.msg === "原密码错误") {
            this.$message.warning("原密码错误");
          } else {
            this.$message.warning("密码修改失败");
          }
        }
      });
    },
    // 重置密码
    resetPassword(row) {
      let params = {
        idList: [row.userId]
      };
      this.$confirm("重置默密码为'@@ssag2613',您确定要重置密码? ", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      }).then(() => {
        UserApi.resetPassword(params).then(res => {
          if (res.success === true) {
            this.assignRoleActive = false
            this.$message.success("重置成功");
            this.resetActionBar()
          } else if (res.success === false && res.errCode === 200) {
            this.$message.warning(res.message);
          }
        });
      }).catch(() => {
        this.resetActionBar()
        this.$message.success("取消重置")
      })
    },
    // 添加用户
    registerIofo(params) {
      params.userType = '1'
      UserApi.add(params).then(res => {
        this.getHomeBase();
        if (res.success === true) {
          this.closeDialog();
          this.queryPageList();
          this.assignRoleActive = false
          this.$message.success("添加成功");
        } else if (res.success === false && res.errCode === 200) {
          this.$message.warning(res.message);
        }
      });
    },
    openDialog(type) {
      this.$refs.formData.resetFields()
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.$refs.formData.resetFields()
      this.dialogFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.dialogTitle = null;
      this.addActive = true;
      this.nowChanceStau = "";
      this.getHomeBase();
    }
  }
};
</script>

<style lang="scss" scoped>
.table-btns {
  padding: 0 10px;
  cursor: pointer;
}

.imageStyle {
  height: 100px;
  width: 200px;
  border-radius: 4px;
  margin: 0 auto;
  background-color: #cecece3f;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 16px;
  color: #999999;
}
</style>
